<template>
  <q-page padding>
    <q-card flat bordered>
      <q-card-section class="row items-center justify-between">
        <div class="row items-center">
          <q-btn
            icon="arrow_back"
            flat
            round
            dense
            class="q-mr-sm"
            @click="handleCancel"
          />
          <div class="text-h6">{{ isEdit ? '编辑展会信息' : '新增展会信息' }}</div>
        </div>
        <q-btn
          v-if="isEdit"
          :label="isEditing ? '取消编辑' : '编辑'"
          :color="isEditing ? 'grey' : 'primary'"
          @click="toggleEdit"
        />
      </q-card-section>

      <q-card-section>
        <q-form  ref="formRef">
          <!-- 添加AI检查状态提示 -->
          <div class="ai-check-alert q-mb-md" v-if="formData.ai_checked_status !== undefined">
            <q-banner
              :class="{
                'bg-grey-2': formData.ai_checked_status === 0,
                'bg-green-1': formData.ai_checked_status === 1,
                'bg-orange-1': formData.ai_checked_status === 2
              }"
              class="ai-check-banner"
              rounded
            >
              <template v-slot:avatar>
                <q-icon
                  :name="formData.ai_checked_status === 0 ? 'pending' : formData.ai_checked_status === 1 ? 'check_circle' : 'warning'"
                  :class="{
                    'text-grey': formData.ai_checked_status === 0,
                    'text-positive': formData.ai_checked_status === 1,
                    'text-warning': formData.ai_checked_status === 2
                  }"
                  size="md"
                />
              </template>
              <div class="ai-check-content">
                <div class="ai-check-status" :class="{
                  'text-grey-8': formData.ai_checked_status === 0,
                  'text-positive': formData.ai_checked_status === 1,
                  'text-warning': formData.ai_checked_status === 2
                }">
                  {{ formData.ai_checked_status === 0 ? '未检查' : formData.ai_checked_status === 1 ? '检查无误' : '检查有问题' }}
                </div>
                错误：<div class="ai-check-description" v-if="formData.error_check_description">
                  {{ formData.error_check_description }}
                </div>
                建议：<div class="ai-check-description" v-if="formData.advice_check_description">
                  {{ formData.advice_check_description }}
                </div>

              </div>
            </q-banner>
          </div>

          <div class="row q-col-gutter-md custom-disabled">
            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.exhibition_number"
                label="审批系统展会编号"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入审批系统展会编号',
                  val => /^\d{1,8}$/.test(val) || '审批系统展会编号必须是1-8位数字'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.chinese_name"
                label="中文名称"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入中文名称',
                  val => /^[\u4e00-\u9fa5A-Z、]+$/.test(val) || '中文名称只能包含汉字、英文大写字母和顿号',
                  val => val.startsWith(formData.country) || `展会名称建议以国别（${formData.country}）开头`
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.english_name"
                label="外文全称"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入外文全称',
                  val => /^[0-9A-Z. +\-'()&,]+$/.test(val) || '外文全称只能包含大写字母、数字、点、空格、连字符、括号、逗号和&符号'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.english_short_name"
                label="外文简称"
                :disable="formFields.disabled"
                :rules="[
                  val => !val || /^[0-9A-Z. +\-]+$/.test(val) || '外文简称只能包含大写字母、数字、点、空格和连字符',
                  val => !val || val !== formData.english_name || '外文简称不能与全称相同'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <div class="row q-col-gutter-sm">
                <div class="col-12">
                  <q-select
                    v-model="holding_time_type"
                    :options="[
                      { label: '标准格式', value: 'standard' },
                      { label: '自定义格式', value: 'custom' }
                    ]"
                    label="举办时间"
                    :disable="formFields.disabled"
                    emit-value
                    map-options
                  />
                </div>
                <div class="col-12">
                  <q-input
                    v-model="formData.holding_time"
                    label=""
                    :disable="formFields.disabled"
                    :rules="[
                      val => !!val || '请输入举办时间',
                      val => {
                        if (holding_time_type === 'standard') {
                          return /^[0-9]+月[0-9]+日-[0-9]+月[0-9]+日$/.test(val) || '举办时间格式为：数字月数字日-数字月数字日'
                        }
                        return true
                      }
                    ]"
                  />
                </div>
              </div>
            </div>

            <div class="col-12 col-md-6">
              <q-select
                v-model="formData.continent"
                :options="['亚洲', '欧洲', '非洲', '北美洲', '南美洲', '大洋洲']"
                label="洲"
                :disable="formFields.disabled"
                :rules="[val => !!val || '请选择洲']"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.country"
                label="国家"
                :disable="formFields.disabled"
                :rules="[val => !!val || '请输入国家']"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.city"
                label="城市"
                :disable="formFields.disabled"
                :rules="[val => !!val || '请输入城市']"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-select
                v-model="formData.frequency"
                :options="['一年一届', '一年两届', '两年一届', '四年一届']"
                label="举办频率"
                :disable="formFields.disabled"
                :rules="[val => !!val || '请选择举办频率']"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-select
                v-model="formData.industry"
                :options="filteredIndustries"
                label="行业"
                :disable="formFields.disabled"
                :rules="[val => !!val || '请选择行业']"
                use-input
                input-debounce="0"
                @filter="filterIndustry"
                @input-value="val => inputValue = val"
                hide-selected
                fill-input
                clearable
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.organizer"
                label="主办方"
                :disable="formFields.disabled"
                :rules="[
                  val => !val || /^[\u4e00-\u9fa5A-Za-zÄÖÜäöüßéèêëàâôûùÿçáíóúñÁÍÓÚÑœæÀÂÆŒÈÉÊËÎÏÔŒÙÛÜŸãõâêôîûáéíóúàèìòùÃÕÂÊÔÎÛÁÉÍÓÚÀÈÌÒÙ&.、 ()]+$/.test(val) || '主办方名称只能包含汉字、大小写字母、德语字母和顿号'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.organizer_en"
                label="主办方外文"
                :disable="formFields.disabled"
                :rules="[
                  val => !val || /^[a-zA-Z&.,/ ()ÄÖÜäöüßéèêëàâôûùÿçáíóúñÁÍÓÚÑœæÀÂÆŒÈÉÊËÎÏÔŒÙÛÜŸãõâêôîûáéíóúàèìòùÃÕÂÊÔÎÛÁÉÍÓÚÀÈÌÒÙ\-']+$/.test(val) || '主办方英文名称格式不正确'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.contact_info"
                label="联系方式"
                :disable="formFields.disabled"
                :rules="[
                  val => !val || /^(\+\d+ \(\d+\) \d{1,4}-\d{4,8}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/.test(val) || '联系方式格式需要是电话号码(+xx (xx) xxx-xxxx)或邮箱地址(xxx@xxx.xxx)'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.exhibition_hall"
                label="展馆"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入展馆',
                  val => val.startsWith(formData.city) || `展馆名称必须以城市名（${formData.city}）开头`
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.exhibition_hall_english"
                label="展馆外文"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入展馆英文名称',
                  val => /^[A-Za-z\-'ÄÖÜäöüßéèêëàâôûùÿçáíóúñÁÍÓÚÑœæÀÂÆŒÈÉÊËÎÏÔŒÙÛÜŸãõâêôîûáéíóúàèìòùÃÕÂÊÔÎÛÁÉÍÓÚÀÈÌÒÙ&., ]+$/.test(val) || '展馆英文名称格式不正确'
                ]"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model="formData.official_website"
                label="官网"
                :disable="formFields.disabled"
                :rules="[
                  val => !val || /^(?:www\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]+(?:\/[a-zA-Z0-9-_/]*)?(?:\.[a-z]+)?$/.test(val) || '官网格式不正确'
                ]"
              />
            </div>

            <div class="col-12">
              <q-input
                v-model="formData.exhibit_scope"
                type="textarea"
                label="展品范围"
                :disable="formFields.disabled"
                :rules="[
                  val => !!val || '请输入展品范围',
                  val => val?.length <= 100 || '展品范围不能超过100字',
                  val => !val?.endsWith('。') || '展品范围不能以句号结尾',
                  val => val === val?.trim() || '展品范围不能有前后空格'
                ]"
                autogrow
              />
            </div>

            <div class="col-12">
              <q-input
                v-model="formData.description"
                type="textarea"
                label="简介"
                :disable="formFields.disabled"
                :rules="[
                  val => !val || val?.length <= 150 || '简介不能超过150字',
                  val => !val?.endsWith('。') || '简介不能以句号结尾',
                  val => !val || val === val?.trim() || '简介不能有前后空格'
                ]"
                autogrow
              />
            </div>

            <div class="col-12 col-md-6">
              <q-select
                v-model="formData.ufi_certified"
                :options="ufiOptions"
                option-value="value"
                option-label="label"
                emit-value
                map-options
                label="是否UFI认证"
                :disable="formFields.disabled"
              />
            </div>

            <div class="col-12 col-md-6">
              <q-input
                v-model.number="formData.exhibition_area"
                label="展会面积"
                :disable="formFields.disabled"
                suffix="㎡"
              />
            </div>
          </div>

          <div class="row q-mt-md justify-end">
            <q-btn
              label="取消"
              color="grey"
              flat
              class="q-mr-sm"
              @click="confirmCancel"
              v-if="!isEdit || isEditing"
            />
            <q-btn
              label="保存"
              color="primary"
              @click="handleSubmit"
              v-if="!isEdit || isEditing"
            />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </q-page>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useQuasar } from 'quasar'
import { getExhibition, createExhibition, updateExhibition } from 'src/api/exhibition'

const $q = useQuasar()
const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const isEdit = ref(false)
const holding_time_type = ref('standard')  // 添加这一行

const ufiOptions = [
  { label: '未知', value: 0 },
  { label: '是', value: 1 },
  { label: '否', value: 2 }
]

// 修改 formData 中的初始值
const formData = ref({
  exhibition_number: '',
  chinese_name: '',
  english_name: '',
  english_short_name: '',
  holding_time: '',
  event_date_end: '',
  event_date_start:'',
  continent: '',
  country: '',
  city: '',
  frequency: '',
  industry: '',
  organizer: '',
  organizer_en: '',
  contact_info: '',
  exhibition_hall: '',
  exhibition_hall_english: '',
  official_website: '',
  exhibit_scope: '',
  description: '',
  ufi_certified: 0,  // 设置默认值为 0（未知）
  exhibition_area: null,
  ai_checked_status: 0,  // 添加AI检查状态，默认为未检查
  error_check_description: '' ,
  advice_check_description: ''  // 添加AI检查描述
})

const industryTypes = ref([
  "农林牧渔",
        "食品饮料",
        "纺织服饰",
        "皮革鞋包",
        "妇婴用品",
        "美容美发",
        "礼品玩具及宠物用品",
        "钟表眼镜",
        "珠宝首饰",
        "生活用品",
        "婚庆用品",
        "酒店用品",
        "办公用品",
        "教育装备",
        "劳保用品",
        "文体娱乐",
        "健康养老",
        "医疗及制药设备",
        "药品及原料",
        "汽车",
        "自行车电动车摩托车",
        "航空航天",
        "船舶和轨道等交通",
        "光电产品",
        "计算机通信及电子设备",
        "仪表仪器",
        "冷暖设备",
        "泵阀管道",
        "五金工具",
        "工业机械",
        "工程机械",
        "农业机械",
        "食品加工设备",
        "采矿及设备",
        "电力及新能源设备",
        "节能环保",
        "化工产品",
        "高新材料 / 技术",
        "其他设备 / 材料",
        "家电",
        "家居家居",
        "建筑建材",
        "物流仓储",
        "电商和交易会",
        "广告传播",
        "印刷包装",
        "公共安全",
        "连锁加盟",
        "综合类",
        "其他"
])

// 修改 getExhibitionDetail 函数
const getExhibitionDetail = async (id) => {
  try {
    const res = await getExhibition(id)
    const data = { ...res.data }
    // 确保 ufi_certified 是数字类型
    data.ufi_certified = Number(data.ufi_certified || 0)
    Object.assign(formData.value, data)

    // 判断举办时间格式并设置对应的类型
    if (data.holding_time) {
      const standardPattern = /^[0-9]+月[0-9]+日-[0-9]+月[0-9]+日$/
      holding_time_type.value = standardPattern.test(data.holding_time) ? 'standard' : 'custom'
    }
  } catch (error) {
    console.error(error)
    $q.notify({
      type: 'negative',
      message: '获取展会信息失败'
    })
  }
}

const isEditing = ref(false)

// 修改所有输入组件，添加 :disable 属性
const formFields = computed(() => {
  const disabled = isEdit.value && !isEditing.value
  return {
    disabled,
    // 可以添加其他通用属性
  }
})

// 添加切换编辑状态的方法
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}



// 修改 filterIndustry 函数
const inputValue = ref('')
const filteredIndustries = ref([...industryTypes.value])

const filterIndustry = (val, update) => {
  if (!val) {
    update(() => {
      filteredIndustries.value = [...industryTypes.value]
    })
    return
  }

  update(() => {
    const needle = val.toLowerCase()
    filteredIndustries.value = industryTypes.value.filter(v => 
      v.toLowerCase().includes(needle)
    )
  })
}



// 修改 handleSubmit
const handleSubmit = async () => {
  try {
    // 先检查举办时间格式
    if (holding_time_type.value === 'standard') {
      const timePattern = /^[0-9]+月[0-9]+日-[0-9]+月[0-9]+日$/
      if (!timePattern.test(formData.value.holding_time)) {
        $q.notify({
          type: 'negative',
          message: '举办时间格式错误，请修正后再提交'
        })
        return
      }
    }
    // 手动触发验证，收集所有错误信息
    const hasError = await formRef.value.validate()
    if (hasError) {
      // 获取所有表单字段的验证信息
      const errorFields = []
      const formElements = formRef.value.$el.querySelectorAll('.q-field--error')
      formElements.forEach(element => {
        const label = element.querySelector('.q-field__label')?.textContent || ''
        const error = element.querySelector('.q-field__messages')?.textContent || ''
        if (label && error) {
          errorFields.push(`${label}: ${error}`)
        }
      })



      // $q.notify({
      //   type: 'warning',
      //   message: '表单存在以下问题，但仍然可以提交：',
      //   caption: errorFields.join('\n'),
      //   multiLine: true,
      //   timeout: 5000,
      //   position: 'top',
      //   html: true
      // })
    }

    const submitData = { ...formData.value }

    if (isEdit.value) {
      await updateExhibition(route.query.id, submitData)
      $q.notify({
        type: 'positive',
        message: '更新成功'
      })
      isEditing.value = false  // 保存成功后退出编辑状态
    } else {
      await createExhibition(submitData)
      $q.notify({
        type: 'positive',
        message: '创建成功'
      })
    }

    router.push('/exhibition')
  } catch (error) {
    console.log(error)
    $q.notify({
      type: 'negative',
      message: '保存失败'
    })
  }
}

// 修改 confirmCancel
const confirmCancel = () => {
  const message = isEdit.value ?
    (isEditing.value ? '确定要取消编辑吗？未保存的内容将会丢失' : '确定要返回列表页吗？') :
    '确定要取消编辑吗？未保存的内容将会丢失'

  $q.dialog({
    title: '确认提示',
    message,
    persistent: true,
    ok: {
      label: '确定',
      color: 'primary'
    },
    cancel: {
      label: '取消',
      color: 'grey'
    }
  }).onOk(() => {
    if (isEdit.value && isEditing.value) {
      isEditing.value = false
      getExhibitionDetail(route.query.id)  // 重新加载数据
    } else {
      handleCancel()
    }
  })
}

const handleCancel = () => {
  router.push({
    path: '/exhibition',
    replace: true
  })
}

onMounted(() => {
  const id = route.query.id
  if (id) {
    isEdit.value = true
    getExhibitionDetail(id)
  }
})

// 添加计算属性：根据开始和结束时间生成 holding_time
const computedHoldingTime = computed(() => {
  if (!formData.value.event_date_start || !formData.value.event_date_end) {
    return ''
  }

  const startDate = new Date(formData.value.event_date_start)
  const endDate = new Date(formData.value.event_date_end)

  return `${startDate.getMonth() + 1}月${startDate.getDate()}日-${endDate.getMonth() + 1}月${endDate.getDate()}日`
})

// 监听计算属性的变化，更新 holding_time
watch(computedHoldingTime, (newValue) => {
  formData.value.holding_time = newValue
})

// 监听 holding_time 的变化，更新开始和结束时间
watch(() => formData.value.holding_time, (newValue) => {
  if (!newValue) return

  const match = newValue.match(/^(\d+)月(\d+)日-(\d+)月(\d+)日$/)
  if (match) {
    const [_, startMonth, startDay, endMonth, endDay] = match
    const currentYear = new Date().getFullYear()

    formData.value.event_date_start = `${currentYear}-${String(startMonth).padStart(2, '0')}-${String(startDay).padStart(2, '0')} 00:00:00`
    formData.value.event_date_end = `${currentYear}-${String(endMonth).padStart(2, '0')}-${String(endDay).padStart(2, '0')} 00:00:00`
  }
})
</script>

<style>
.q-field--disabled {
  cursor: default !important;
  opacity: 1 !important;
}
.q-field--disabled * {
  cursor: default !important;
  color: rgba(0, 0, 0, 0.9) !important;
}
.q-field--disabled .q-field__label {
  color: rgba(0, 0, 0, 0.6) !important;
}

/* AI检查提示样式 */
.ai-check-alert {
  .ai-check-banner {
    padding: 16px;
    transition: all 0.3s ease;

    &:deep(.q-banner__avatar) {
      min-width: 48px;
    }

    .q-icon {
      font-size: 32px;
    }
  }

  .ai-check-content {
    .ai-check-status {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 4px;
    }

    .ai-check-description {
      font-size: 14px;
      color: #666;
      line-height: 1.5;
      white-space: pre-line;
    }
  }
}

/* 修改验证规则提示的颜色 */
.q-field__messages {
  color: #c5735a !important;
}





.q-field--error .q-field__control {
  color: #7a7976 !important;
}
</style>



